$(document).ready(function(){
$('#start_date').datetime({ withTime: false, format: 'yy-mm-dd' });
$('#end_date').datetime({ withTime: false, format: 'yy-mm-dd' });


$('input[name=unit_text]').click(function() {
	var that = $(this);
	var top = that.offset().top + 32;
	var left = that.offset().left;
	$.get('/traffic/bandwidth_unit/?service_id='+$('#service_id').val(), function (data) {
		$.blockUI({
			'message': data,
			css: { 
				textAlign:'left',
                width: '500px', 
				height: '300px',
                padding: '5px', 
                '-webkit-border-radius': '10px', 
                '-moz-border-radius': '10px', 
				'top': top,
				'left': left,
				'cursor': 'default'
            },
			overlayCSS:  { 
                backgroundColor: '#fff',
				'cursor': 'default'
			} 
			});	
		$('input[name=checkall]').click(function() {
			if ($(this).attr('checked') == 'checked') {
				$('input.unit_item').attr('checked', 'checked');
			} else {
				$('input.unit_item').removeAttr('checked');
			}
		});
		$('div.done').click(function() {
			var r = [];
			var t = [];
			$('input.unit_item').each(function(i){
				if ($(this).attr('checked') == 'checked') {
					r.push($(this).val());
					t.push($(this).attr('title'));
				}
			});
			$('input[name=unit]').val(r.join('_'));
			$('input[name=unit_text]').val(t.join(','));
			$.unblockUI();
		});
	}, 'html');	
});

$('#search').submit(function() {
	var msg = '错误信息:'+"\n";

	var unit = $('input[name=unit]').val();
	var unit_flag = true;
	if (unit == '') {
		msg += '请选择计费单元'+"\n";
		unit_flag = false;	
	}

	var service_id = $('#service_id').val();
	var service_flag = true;
/*
	if (service_id == 0) {
		msg += '请选择业务类型'+"\n";
		service_flag = false;	
	}	
*/
	var start = $('#start_date').val();
	var start_flag = true;
	if (start == '') {
		msg += '请选择起始时间'+"\n";
		start_flag = false;
	}
	var end = $('#end_date').val();
	var end_flag = true;
	if (end == '') {
		msg += '请选择起始时间'+"\n";
		end_flag = false;
	}
	if (unit_flag && service_flag && start_flag && end_flag) {
		var queryString = $('#search').formSerialize();
		$.post('/traffic/bandwidth_chart/', queryString, function(data) {
			$.blockUI({'message': 'Loading ...'});
			$('#summary').html('<span>您查询 '+start+' 至 '+end+' 的带宽图如下:</span><br /><br /<span>本次查询的峰值时间：'+data[0].peak_time+ ' 峰值带宽：'+data[0].peak + 'Mbps' + ' 收费带宽 ' + data[0].charge_bandwidth.traffic + ' 总下载量:'+ data[0].total).show();
			//$('#placeholder').empty();
			//$('tr.data').remove();
			var d = new Array();
			$.each(data, function(index, value) {
				d.push({'label':value.info, 'data':value.data, 'lines':{'fill': true}});
				//$('#tableholder table').append('<tr class="data"><td>'+value.info.unit+'</td><td>'+value.peak+'</td><td>'+value.total+'</td><td>'+value.peak_time+'</td></tr>');
			});
			//$('#tableholder').show();
			$.plot($("#placeholder"), d, { legend: {
show: true,
margin: 10,
backgroundOpacity: 0.5
},grid: { hoverable: true, clickable: true },xaxis: { mode: "time",timeformat: "%y/%m/%d" } });
    function showTooltip(x, y, contents) {
        $('<div id="tooltip">' + contents + '</div>').css( {
            position: 'absolute',
            display: 'none',
            top: y + 5,
            left: x + 5,
            //border: '1px solid #fdd',
            padding: '2px',
            'background-color': '#fff',
            opacity: 0.80
        }).appendTo("body").fadeIn(200);
    }

    var previousPoint = null;
    $("#placeholder").bind("plothover", function (event, pos, item) {
        $("#x").text(pos.x.toFixed(2));
        $("#y").text(pos.y.toFixed(2));

        //if ($("#enableTooltip:checked").length > 0) {
		if (true) {
            if (item) {
                if (previousPoint != item.dataIndex) {
                    previousPoint = item.dataIndex;
                    
                    $("#tooltip").remove();
                    var x = item.datapoint[0].toFixed(0),
                        y = item.datapoint[1].toFixed(2);
                   	var d = new Date();
					d.setTime(x);
					x = d.pattern('yyyy-MM-dd H:m'); 
                    //showTooltip(item.pageX, item.pageY,item.series.label + " of " + x + " = " + y);
                    showTooltip(item.pageX, item.pageY,x + ' ' + y);
                }
            }
            else {
                $("#tooltip").remove();
                previousPoint = null;            
            }
        }
    });
		$.unblockUI();
		}, 'json');
	} else {
		alert(msg);
	}
	return false;
});

Date.prototype.pattern=function(fmt) {     
    var o = {     
    "M+" : this.getMonth()+1, //月份     
    "d+" : this.getDate(), //日     
    "h+" : this.getHours()%12 == 0 ? 12 : this.getHours()%12, //小时     
    "H+" : this.getHours(), //小时     
    "m+" : this.getMinutes(), //分     
    "s+" : this.getSeconds(), //秒     
    "q+" : Math.floor((this.getMonth()+3)/3), //季度     
    "S" : this.getMilliseconds() //毫秒     
    };     
    var week = {     
    "0" : "\u65e5",     
    "1" : "\u4e00",     
    "2" : "\u4e8c",     
    "3" : "\u4e09",     
    "4" : "\u56db",     
    "5" : "\u4e94",     
    "6" : "\u516d"    
    };     
    if(/(y+)/.test(fmt)){     
        fmt=fmt.replace(RegExp.$1, (this.getFullYear()+"").substr(4 - RegExp.$1.length));     
    }     
    if(/(E+)/.test(fmt)){     
        fmt=fmt.replace(RegExp.$1, ((RegExp.$1.length>1) ? (RegExp.$1.length>2 ? "\u661f\u671f" : "\u5468") : "")+week[this.getDay()+""]);     
    }     
    for(var k in o){     
        if(new RegExp("("+ k +")").test(fmt)){     
            fmt = fmt.replace(RegExp.$1, (RegExp.$1.length==1) ? (o[k]) : (("00"+ o[k]).substr((""+ o[k]).length)));     
        }     
    }     
    return fmt;     
} 

var today = new Date();
var yesterday = new Date();
yesterday.setTime(yesterday.getTime()-24*60*60*1000);
var monday = new Date();
monday.setTime(monday.getTime() - 24*60*60*1000*monday.getDay());
var month = new Date();
month.setTime(month.getTime() - 24*60*60*1000*(month.getDate()-1));

var last_month_end = new Date();
last_month_end.setDate(1);
last_month_end.setTime(last_month_end.getTime() - 24*60*60*1000);

var last_month_start = new Date();
last_month_start.setMonth(last_month_start.getMonth() -1);
last_month_start.setDate(1);

$('a.today').click(function() {
	$('#start_date').val(today.pattern("yyyy-MM-dd"));
	$('#end_date').val(today.pattern("yyyy-MM-dd"));
});
$('a.yesterday').click(function() {
	$('#start_date').val(yesterday.pattern("yyyy-MM-dd"));
	$('#end_date').val(yesterday.pattern("yyyy-MM-dd"));
});
$('a.week').click(function() {
	$('#start_date').val(monday.pattern("yyyy-MM-dd"));
	$('#end_date').val(today.pattern("yyyy-MM-dd"));
});
$('a.month').click(function() {
	$('#start_date').val(month.pattern("yyyy-MM-dd"));
	$('#end_date').val(today.pattern("yyyy-MM-dd"));
});
$('a.last_month').click(function() {
	$('#start_date').val(last_month_start.pattern("yyyy-MM-dd"));
	$('#end_date').val(last_month_end.pattern("yyyy-MM-dd"));
});

});
